package com.smsVerification.controller;

import com.smsVerification.config.HttpCode;
import com.smsVerification.pojo.CommonResult;
import com.smsVerification.pojo.UserAuthVO;
import com.smsVerification.service.login.ILoginService;
import com.smsVerification.utils.EncryptValueHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


@RefreshScope
@RestController
public class LoginController {

    final String REQUEST_URL_PREFIX = "/user-auth/Login";

    /**
     * 用户信息AES加密秘钥
     */
    @Value("${user-info.aes-encrypt-key}")
    String userInfoAesEncryptKey;

    /**
     * 用户信息AES加密加盐偏移
     */
    @Value("${user-info.aes-encrypt-iv}")
    String userInfoAesEncryptIv;

    @Resource
    ILoginService loginService;

    /**
     * 验证码登录
     *
     * @param encryptedPhoneNumber 加密的手机号
     * @param encryptedCaptcha     加密的验证码
     * @return 用户身份数据
     */
    @PostMapping(REQUEST_URL_PREFIX + "/loginByCaptcha")
    public CommonResult<UserAuthVO> loginByCaptcha(@RequestParam("encryptedPhoneNumber") String encryptedPhoneNumber, @RequestParam("encryptedCaptcha") String encryptedCaptcha) {

        //解密后的手机号
        String decryptedPhoneNumber = getDecryptUserInfoData(encryptedPhoneNumber);
        //解密后的验证码
        String decryptedCaptchaString = getDecryptUserInfoData(encryptedCaptcha);

        if (decryptedPhoneNumber == null || decryptedCaptchaString == null) {
            return new CommonResult<>(HttpCode.WRONG_PARAM, "参数错误", null);
        }

        //验证码类型转换
        int decryptedCaptcha;
        try {
            decryptedCaptcha = Integer.parseInt(decryptedCaptchaString);
        } catch (Exception e) {
            return new CommonResult<>(HttpCode.WRONG_PARAM, "参数错误", null);
        }

        return loginService.loginByCaptcha(decryptedPhoneNumber, decryptedCaptcha);

    }

    /**
     * 极光认证一键登录
     * 参考文档：https://docs.jiguang.cn/jverification/server/rest_api/loginTokenVerify_api
     *
     * @param loginToken 极光认证一键登录的秘钥
     * @return 用户身份数据
     */
    @PostMapping(REQUEST_URL_PREFIX + "/loginByJverify")
    public CommonResult<UserAuthVO> loginByJverify(@RequestBody String loginToken) {
        return loginService.loginByJverify(loginToken);

    }

    /**
     * 将用户加密的数据进行解密
     *
     * @param encryptedData 加密的数据
     * @return 解密的数据
     */
    private String getDecryptUserInfoData(String encryptedData) {
        return EncryptValueHandler.getAesCbcDecryptData(userInfoAesEncryptKey, userInfoAesEncryptIv, encryptedData);
    }

}
